package com.woniu.common;

import com.woniu.pojo.Book;
import com.woniu.redis.RedisConst;
import com.woniu.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class StorageRunner implements CommandLineRunner {
    @Autowired
    private BookService bookService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 判断 redis是否已经包含 库存数据
        if (!redisTemplate.hasKey(RedisConst.BOOK_STORAGE)) {
            // 没有数据，进行数据库查询，并且添加之redis操作
            log.info("redis 中没有库存数据，正在添加...");
            List<Book> list = bookService.list();   // 查询所有图书

            // 存入redis、
            // 获取操作hash数据的对象、
            HashOperations ops = redisTemplate.opsForHash();
            list.forEach(
                    book -> {
                    // 将book存入 redis
                        String hashKey = book.getId().toString();
                        Integer hashValue = book.getStoreCount();
                        ops.put(RedisConst.BOOK_STORAGE,hashKey,hashValue); // key    hashKey   hashValue
                    }
            );
            log.info("库存初始化完成！");
        }
    }
}
